package layeredcontent.domains.account.model
{
	import flash.events.Event;
	
	import flight.net.IResponse;
	import flight.net.Response;
	import flight.vo.ValueObject;
	
	import withincode.db.Database;
	import withincode.filesystem.AsyncFile;
	
	[Bindable]
	public class Account extends ValueObject
	{
		public static const DATABASE_FILE:String = "data.db";
		public var name:String;
		protected var directory:AsyncFile;
		protected var database:Database;
		
		
		public function Account(name:String = null)
		{
			this.name = name;
		}
		
		public function open():IResponse
		{
			//directory = File.applicationStorageDirectory.resolvePath("accounts/" . name);
			
			if (!directory.exists) {
				directory.createDirectory();
				
			}
			
			return new Response(this, Event.OPEN);
		}
		
		/**
		 * Saves the account to the system.
		 */
		public function create():IResponse
		{
			directory = AsyncFile.applicationStorageDirectory.resolvePath("accounts/" + name);
			directory.createDirectory();
			database = new Database("accounts/" + name);
			database.open(directory.resolvePath(DATABASE_FILE).file).addResultHandler(createDatabase);
			
			return new Response();
		}
		
		protected function createDatabase(database:Database):void
		{
			var sqlFile:AsyncFile = AsyncFile.applicationDirectory.resolvePath("assets/schema.sql");
			sqlFile.read().addResultHandler(runSQL);
		}
		
		protected function runSQL(sql:String):void
		{
			trace(sql);
		}
	}
}